/**
 * @author luzeyu & liangqiaowei
 */
package tiei.ajp.huffman.utils;

import java.io.*;

public class BitInputStream {
    private InputStream input = null;
    private int currentByte; // Data of current byte, -1 for EOF
    private int bitPosition; // Next bit index [0...7] to read from
    private long bitCounter; // Num of bits that have read
    private static final int EOF = -1;
    private static final int BIT_O = 0;
    private static final int BIT_1 = 1;
    private static final int HSB_MASK = 0b10000000000000000000000000000000;
    private static final int LSB_MASK = 0b00000000000000000000000000000001;

    public BitInputStream(File file) throws IOException {
        this.input = new BufferedInputStream(new FileInputStream(file));
        currentByte = input.read();
        bitPosition = 0;
        bitCounter = 0L;
    }

    public int readBit() throws IOException {
        if (currentByte == EOF) {
            return EOF;
        }

        int bit = (currentByte << bitPosition) & HSB_MASK;
        bitPosition++;

        // Check if read full byte
        if (bitPosition == 8) { // 读取完一个字节
            currentByte = input.read();
            bitPosition = 0;
        }

        bitCounter++;
        return bit;
    }

    public long getReadBitsNum() {
        return bitCounter;
    }

    public void close() throws IOException {
        input.close();
    }
}

